package com.lw.security.security.service;

import com.lw.security.mapper.UserMapper;
import com.lw.security.pojo.User;
import com.lw.security.security.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/28 21:59
 *
 * 当前类的作用，根据用户名查询用户数据
 */
@Component
public class MyUserSetailService implements UserDetailsService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * @param username 当我们登录的时候传递过来的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUserName(username);
        //如果用户不存在
        if(user==null){
            throw new UsernameNotFoundException("用户名密码不存在");
        }

        if(user.getStatus()==0){
            throw new AccountExpiredException("账号过期");
        }
        if(user.getStatus()==1){
            throw new LockedException("账号被封禁");
        }

        //参数1 当前的用户名
        //参数2 数据库中查询到的密码
        //参数3 用户有的权限
        return new BaseUser(username,user.getPassword(),new ArrayList<>(),user.getUserId());
    }
}
